<template>
  <div class="front-home">
<!--     轮播图
    <div class="carousel-section">
      <el-carousel height="400px">
        <el-carousel-item v-for="item in carousels" :key="item.id" class="carousel-item">
          <el-image
            :src="getImageUrl(item.imageUrl)"
            :alt="item.title"
            fit="cover"
            :fallback="defaultImage">
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>加载失败</span>
              </div>
            </template>
            <template #placeholder>
              <div class="image-placeholder">
                <el-icon><Loading /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="carousel-caption">
            <h3>{{ item.title }}</h3>
            <p>{{ item.description }}</p>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>-->

    <!-- 内容区域 -->
    <div class="content">

      <!-- 最新公告 -->
      <section class="section announcement-section">
        <div class="section-header">
          <h2>最新公告</h2>
          <router-link to="/front/announcements">查看更多</router-link>
        </div>
        <el-card class="announcement-list">
          <div
              v-for="item in announcements"
              :key="item.id"
              class="announcement-item"
              @click="handleAnnouncementClick(item)"
          >
            <div class="title">
              <el-icon><Bell /></el-icon>
              {{ item.title }}
            </div>
            <div class="time">{{ formatDate(item.createTime) }}</div>
          </div>
        </el-card>
      </section>
      <!-- 新闻资讯 -->
      <section class="section news-section">
        <div class="section-header">
          <h2>新闻资讯</h2>
          <router-link to="/front/news">查看更多</router-link>
        </div>
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in news" :key="item.id">
            <el-card class="news-card" shadow="hover" @click="handleNewsClick(item)">
              <img :src="item.image" class="news-image">
              <div class="news-info">
                <h3>{{ item.title }}</h3>
                <p>{{ item.summary }}</p>
                <div class="news-meta">
                  <span>{{ formatDate(item.createTime) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </section>

      <!-- 热门问卷 -->
      <section class="section questionnaire-section">
        <div class="section-header">
          <h2>热门问卷</h2>
          <router-link to="/front/questionnaires">查看更多</router-link>
        </div>
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in questionnaires" :key="item.id">
            <el-card class="questionnaire-card" shadow="hover">
              <h3>{{ item.title }}</h3>
              <p>{{ item.description }}</p>
              <div class="card-footer">
                <span>{{ formatDate(item.createTime) }}</span>
                <el-button
                  :type="questionnaireStore.isSubmitted(item.id) ? 'success' : 'primary'"
                  @click="handleFill(item)"
                >
                  {{ getButtonText(item) }}
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </section>
    </div>

    <!-- 答案详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="提交记录"
      width="50%"
    >
      <div v-if="currentQuestionnaire" class="submission-details">
        <h3>{{ currentQuestionnaire.title }}</h3>
        <div class="description" v-if="currentQuestionnaire.description">
          {{ currentQuestionnaire.description }}
        </div>
        <div v-for="(question, qIndex) in currentQuestionnaire.questions" :key="qIndex" class="answer-item">
          <div class="question">
            <span class="question-number">{{ qIndex + 1 }}. </span>
            {{ question.title }}
            <span v-if="question.required" class="required">*</span>
          </div>
          <div class="answer">
            <template v-if="question.type === 1"> <!-- 单选题 -->
              <el-tag v-if="getAnswer(question.id) !== null" class="answer-tag">
                {{ getOptionLabel(question, getAnswer(question.id)) }}
              </el-tag>
              <el-tag v-else type="info">未作答</el-tag>
            </template>
            <template v-else-if="question.type === 2"> <!-- 多选题 -->
              <template v-if="getAnswer(question.id)?.length">
                <el-tag 
                  v-for="(optionId, index) in getAnswer(question.id)"
                  :key="index"
                  class="answer-tag"
                >
                  {{ getOptionLabel(question, optionId) }}
                </el-tag>
              </template>
              <el-tag v-else type="info">未作答</el-tag>
            </template>
            <template v-else-if="question.type === 3"> <!-- 填空题 -->
              <div class="text-answer">
                {{ getAnswer(question.id) || '未作答' }}
              </div>
            </template>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Bell, Picture, Loading } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { getCarousels } from '@/api/carousel'
import { getSubmission } from '@/api/questionnaire'
import { useQuestionnaireStore } from '@/stores/questionnaire'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

// 使用 Base64 编码的简单占位图
const defaultImage = ''

const router = useRouter()
const questionnaireStore = useQuestionnaireStore()
const userStore = useUserStore()

const carousels = ref([])
const news = ref([])
const announcements = ref([])
const questionnaires = ref([])

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  const baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8080'
  const path = url.startsWith('/') ? url : `/${url}`
  return `${baseUrl}${path}`
}

const loadData = async () => {
  try {
    // 加载新闻
    const newsRes = await request.get('/api/news/latest')
    if (newsRes.code === 200) {
      news.value = newsRes.data
    }

    // 加载公告
    const announcementRes = await request.get('/api/announcement/latest')
    if (announcementRes.code === 200) {
      announcements.value = announcementRes.data
    }

    // 加载问卷
    const questionnaireRes = await request.get('/api/questionnaire/latest')
    if (questionnaireRes.code === 200) {
      questionnaires.value = questionnaireRes.data
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const loadCarousels = async () => {
  try {
    const res = await getCarousels()
    if (res.code === 200) {
      carousels.value = res.data
    }
  } catch (error) {
    console.error('Failed to load carousels:', error)
  }
}

const handleNewsClick = (news) => {
  router.push(`/front/news/${news.id}`)
}

const handleAnnouncementClick = (announcement) => {
  router.push(`/front/announcements/${announcement.id}`)
}

const handleFill = async (questionnaire) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再填写问卷')
    router.push({
      path: '/login',
      query: { redirect: `/front/questionnaires/${questionnaire.id}/fill` }
    })
    return
  }

  // 如果已提交，显示提交记录
  if (questionnaireStore.isSubmitted(questionnaire.id)) {
    await showSubmission(questionnaire.id)
  } else {
    // 未提交，跳转到填写页面
    router.push(`/front/questionnaires/${questionnaire.id}/fill`)
  }
}

const handleImageError = (error) => {
  console.error('图片加载失败:', error)
}

onMounted(() => {
  loadData()
  loadCarousels()
  if (userStore.isLoggedIn) {
    questionnaireStore.loadSubmittedQuestionnaires()
  }
})

const getButtonText = (questionnaire) => {
  if (questionnaireStore.isSubmitted(questionnaire.id)) {
    return '查看提交'
  }
  return '立即填写'
}

const dialogVisible = ref(false)
const currentQuestionnaire = ref(null)
const currentAnswers = ref(null)

const parsedAnswers = computed(() => {
  if (!currentAnswers.value) return []
  try {
    // 解析答案
    const answersObj = JSON.parse(currentAnswers.value)
    // 处理不同的答案格式
    let normalizedAnswers = answersObj
    if (answersObj.answers) {
      normalizedAnswers = answersObj.answers
    }
    // 获取问卷中的问题
    const questions = currentQuestionnaire.value.questions || []

    return questions.map(question => {
      const answer = normalizedAnswers[question.id]
      if (!answer) return {
        question: question.title,
        answer: ['未作答']
      }
      return {
        question: question.title,
        answer: Array.isArray(answer) ? answer : answer ? [answer] : ['未作答']
      }
    })
  } catch (e) {
    console.error('解析答案失败:', e, currentAnswers.value)
    return []
  }
})

const showSubmission = async (questionnaireId) => {
  try {
    const res = await getSubmission(questionnaireId)
    if (res.code === 200) {
      currentQuestionnaire.value = res.data.questionnaire
      currentAnswers.value = res.data.answers
      console.log('问卷数据:', res.data.questionnaire)
      console.log('答案数据:', res.data.answers)
      console.log('问题列表:', res.data.questionnaire.questions)
      console.log('解析后的答案:', currentAnswers.value)
      dialogVisible.value = true
      return true
    }
    ElMessage.warning('未找到提交记录')
    return false
  } catch (error) {
    console.error('加载提交记录失败:', error)
    ElMessage.error('加载提交记录失败')
    return false
  }
}

// 获取答案
const getAnswer = (questionId) => {
  if (!currentAnswers.value) return null
  try {
    let answers = currentAnswers.value
    // 如果是字符串，尝试解析
    if (typeof answers === 'string') {
      answers = JSON.parse(answers)
    }
    
    // 检查是否有 answers 属性
    if (answers.answers) {
      answers = answers.answers
    }
    
    // 获取特定问题的答案
    let answer = answers[questionId]
    if (!answer) {
      // 尝试使用 'q' + questionId 的格式
      answer = answers[`q${questionId}`]
    }
    
    if (answer === undefined || answer === null) {
      return null
    }
    
    // 如果是数组，直接返回
    if (Array.isArray(answer)) {
      return answer
    }
    
    // 如果是字符串（填空题答案），直接返回
    if (typeof answer === 'string') {
      return answer
    }
    
    // 如果是数字（单选题答案），返回数组形式
    if (typeof answer === 'number') {
      return answer
    }
    
    return null
  } catch (e) {
    console.error('获取答案失败:', e, currentAnswers.value)
    return null
  }
}

// 获取选项标签
const getOptionLabel = (question, optionId) => {
  if (question.type === 3) {
    // 如果是填空题，直接返回答案内容
    return optionId
  }
  
  // 对于单选和多选题，查找选项内容
  const option = question.options?.find(opt => opt.id == optionId) // 使用宽松相等
  return option ? option.content : optionId
}
</script>

<style lang="scss" scoped>
.front-home {
  .carousel-section {
    margin-bottom: 30px;

    .carousel-item {
      height: 400px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .carousel-caption {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      padding: 20px;

      h3 {
        margin: 0;
        font-size: 24px;
      }

      p {
        margin: 10px 0 0;
        font-size: 16px;
      }
    }

    .image-error {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #909399;
      background: #f5f7fa;

      .el-icon {
        font-size: 48px;
        margin-bottom: 10px;
      }
    }
  }

  .content {
    max-width: 1200px;
    margin: 0 auto;

    .section {
      margin-bottom: 40px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        h2 {
          font-size: 24px;
          margin: 0;
          color: #303133;
        }

        a {
          color: #409EFF;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }

    .news-card {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-5px);
      }

      .news-image {
        width: 100%;
        height: 200px;
        object-fit: cover;
      }

      .news-info {
        padding: 15px;

        h3 {
          margin: 0 0 10px;
          font-size: 18px;
          color: #303133;
        }

        p {
          margin: 0 0 10px;
          color: #606266;
          line-height: 1.6;
        }

        .news-meta {
          color: #909399;
          font-size: 14px;
        }
      }
    }

    .announcement-list {
      .announcement-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px;
        cursor: pointer;
        transition: all 0.3s;

        &:not(:last-child) {
          border-bottom: 1px solid #ebeef5;
        }

        &:hover {
          background-color: #f5f7fa;
        }

        .title {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #303133;

          .el-icon {
            color: #409EFF;
          }
        }

        .time {
          color: #909399;
          font-size: 14px;
        }
      }
    }

    .questionnaire-card {
      height: 100%;
      display: flex;
      flex-direction: column;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-5px);
      }

      h3 {
        margin: 0 0 10px;
        font-size: 18px;
        color: #303133;
      }

      p {
        flex: 1;
        margin: 0 0 15px;
        color: #606266;
        line-height: 1.6;
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        span {
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }
}

.submission-details {
  .question {
    font-weight: bold;
    margin-bottom: 10px;
    
    .question-number {
      color: #409EFF;
      margin-right: 5px;
    }
    
    .required {
      color: #F56C6C;
      margin-left: 4px;
    }
  }
  
  .answer {
    margin-bottom: 20px;
    padding-left: 20px;
    
    .answer-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
    
    .text-answer {
      color: #606266;
      line-height: 1.6;
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}
</style>
